package com.jplus.service.impl;

import com.jplus.VO.ResultVO;
import com.jplus.dao.UserDao;
import com.jplus.dao.UserInfoDao;
import com.jplus.entity.User;
import com.jplus.enums.ResultEnum;
import com.jplus.exception.SFUmbrellaException;
import com.jplus.listener.MySessionContext;
import com.jplus.service.LoginService;
import com.jplus.utils.IpUtils;
import com.jplus.utils.ResultVOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserDao userDao;

    @Override
    public ResultVO loginAction(User user, HttpSession session, HttpServletRequest request) {
        try {
            User u = userDao.getUserByPhone(user.getPhone());
            if (u == null) {
                log.error("数据库查不到用户{}", user.getPhone());
                throw new SFUmbrellaException(ResultEnum.USER_NOT_IN_DB);
            } else {
                if (u.getPassword().equals(user.getPassword())) {
                    // 更新用户状态
                    u.setLoginTime(new Date());
                    u.setLoginNum(u.getLoginNum() + 1);
                    u.setLoginIp(IpUtils.getIpAdrress(request));
                    userDao.updateOneUserById(u);
                    if (u.getAdmin().equals(1)) {
                        // 设置管理员登录
                        session.setAttribute("admin", u);
                    } else {
                        // 设置普通用户登录
                        session.setAttribute("customer", u);
                        /**
                         * 小程序的跨域登录有问题，目前暂时用一个危险的方案：使用sessionId保存用户登录状态
                         */
                        String sessionId = session.getId();
                        u.setSessionId(sessionId);
                    }
                    log.info("用户：{}登录成功，时间：{}", user.getPhone(), new Date());
                    return ResultVOUtils.success(u);
                } else {
                    log.error("用户：{}登录出错，时间：{}", user.getPhone(), new Date());
                    return ResultVOUtils.error(0, "登录出错", "用户名或密码不对");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("{}登录失败{}", user.getPhone(), e.getMessage());
            throw new SFUmbrellaException(ResultEnum.LOGIN_FAIL);
        }

    }

    @Override
    public ResultVO logOutAction(String sessionId) {
        // 1.获取登录信息
        MySessionContext myc= MySessionContext.getInstance();
        // 通过sessionId拿到用户登录状态
        HttpSession session = myc.getSession(sessionId);

        try {
            boolean customer = true;
            User user = (User) session.getAttribute("customer");
            if (user == null) {
                user = (User) session.getAttribute("admin");
                customer = false;
            }
            user.setLastLoginTime(user.getLoginTime());
            user.setLastLoginIp(user.getLoginIp());
            userDao.updateOneUserById(user);
            if (customer) {
                // 当session里面不存在这些东西的时候就抛异常
                session.removeAttribute("customer");
            } else {
                session.removeAttribute("admin");
            }
            log.info("登出成功");
            return ResultVOUtils.success("登出成功");
        } catch (Exception e) {
            // 登出失败
            log.error("登出失败，时间：{}", new Date());
            throw new SFUmbrellaException(ResultEnum.LOGOUT_FAILED);
        }
    }
}

